using Intelli.Cust.Svcs.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Json;
using System.Text;

namespace Intelli.Cust.Svcs.Services
{
    public class IntelligentCustomerService : IIntelligentCustomerService
    {
        private readonly ILogger<IntelligentCustomerService> _logger;
        private readonly IOptions<AppSettings> _settings;
        private readonly IMemoryCache _cache;
        private readonly HttpClient _httpClient;
        private readonly Dictionary<string, List<ConversationHistory>> _conversationStore;
        private readonly object _lockObject = new();

        public IntelligentCustomerService(
            ILogger<IntelligentCustomerService> logger,
            IOptions<AppSettings> settings,
            IMemoryCache cache,
            HttpClient httpClient)
        {
            _logger = logger;
            _settings = settings;
            _cache = cache;
            _httpClient = httpClient;
            _conversationStore = new Dictionary<string, List<ConversationHistory>>();
        }

        public async Task<CustomerServiceResponse> ProcessUserInputAsync(string userId, string input, string sessionId)
        {
            try
            {
                _logger.LogInformation("处理用户输入: UserId={UserId}, SessionId={SessionId}, Input={Input}", 
                    userId, sessionId, input);

                // 1. 保存用户输入到对话历史
                var userHistory = new ConversationHistory
                {
                    SessionId = sessionId,
                    UserId = userId,
                    UserInput = input,
                    Timestamp = DateTime.UtcNow
                };

                SaveConversationHistory(sessionId, userHistory);

                // 2. 分析用户意图（保留原先意图，供建议操作等使用）
                var intent = await AnalyzeUserIntentAsync(input, sessionId);
                
                // 3. 生成回复（优先使用LLM，失败或未配置时退回规则）
                var response = await GenerateResponseAsync(input, intent, sessionId);
                
                // 4. 保存助手回复到对话历史
                userHistory.AssistantResponse = response.Content;
                userHistory.IsProcessed = true;

                // 5. 检查是否需要人工干预
                if (response.RequiresHumanIntervention)
                {
                    _logger.LogWarning("需要人工干预: SessionId={SessionId}, Reason={Reason}", 
                        sessionId, response.ErrorMessage);
                }

                return response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理用户输入时发生错误: UserId={UserId}, SessionId={SessionId}", userId, sessionId);
                
                return new CustomerServiceResponse
                {
                    Content = "抱歉，处理您的请求时出现了问题。请稍后重试或联系人工客服。",
                    Type = ResponseType.Error,
                    RequiresHumanIntervention = true,
                    ErrorMessage = ex.Message
                };
            }
        }

        public Task<List<ConversationHistory>> GetConversationHistoryAsync(string sessionId, int limit = 10)
        {
            lock (_lockObject)
            {
                if (_conversationStore.TryGetValue(sessionId, out var history))
                {
                    return Task.FromResult(history.TakeLast(limit).ToList());
                }
                return Task.FromResult(new List<ConversationHistory>());
            }
        }

        public Task RateResponseAsync(string sessionId, string messageId, int rating, string? feedback = null)
        {
            lock (_lockObject)
            {
                if (_conversationStore.TryGetValue(sessionId, out var history))
                {
                    var message = history.FirstOrDefault(h => h.Id == messageId);
                    if (message != null)
                    {
                        message.UserRating = rating;
                        message.UserFeedback = feedback;
                        _logger.LogInformation("用户评价: SessionId={SessionId}, MessageId={MessageId}, Rating={Rating}", 
                            sessionId, messageId, rating);
                    }
                }
                return Task.CompletedTask;
            }
        }

        public Task InitializeKnowledgeBaseAsync()
        {
            try
            {
                _logger.LogInformation("初始化知识库...");
                
                // 这里可以添加初始化向量数据库的逻辑
                // 例如：创建集合、添加初始文档等
                
                _logger.LogInformation("知识库初始化完成");
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化知识库时发生错误");
                throw;
            }
        }

        public Task AddKnowledgeDocumentAsync(string document, Dictionary<string, object> metadata)
        {
            try
            {
                _logger.LogInformation("添加知识库文档: Document={DocumentLength}, Metadata={Metadata}", 
                    document.Length, JsonSerializer.Serialize(metadata));
                
                // 这里可以添加向向量数据库添加文档的逻辑
                // 例如：文本分块、向量化、存储等
                
                _logger.LogInformation("知识库文档添加完成");
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加知识库文档时发生错误");
                throw;
            }
        }

        private Task<string> AnalyzeUserIntentAsync(string input, string sessionId = "")
        {
            // 简单的意图分析逻辑 + 肯定回应承接
            var lowerInput = input.ToLower().Trim();

            // 1) 肯定/继续类回应，承接上一轮语境
            var affirmatives = new[] { "是", "好的", "好", "嗯", "继续", "确认", "可以", "没问题", "行", "嗯嗯", "yes", "ok", "okay", "yeah", "sure", "fine", "continue", "go on" };
            if (affirmatives.Any(a => lowerInput == a || lowerInput.Contains(a)))
            {
                // 扩大回溯范围：回溯最近N条机器消息，寻找待承接的询问
                var pendingIntent = FindPendingIntentFromHistory(sessionId);
                if (!string.IsNullOrWhiteSpace(pendingIntent))
                {
                    return Task.FromResult(pendingIntent);
                }
                // 默认承接为生产信息查询
                return Task.FromResult("query_production");
            }
            
            // 2) 正常关键词匹配
            if (lowerInput.Contains("产量") || lowerInput.Contains("生产"))
                return Task.FromResult("query_production");
            if (lowerInput.Contains("工单") || lowerInput.Contains("创建"))
                return Task.FromResult("create_work_order");
            if (lowerInput.Contains("报警") || lowerInput.Contains("故障"))
                return Task.FromResult("handle_alarm");
            if (lowerInput.Contains("手册") || lowerInput.Contains("说明"))
                return Task.FromResult("view_manual");
            if (lowerInput.Contains("计划") || lowerInput.Contains("调度"))
                return Task.FromResult("adjust_schedule");
            if (lowerInput.Contains("状态"))
                return Task.FromResult("query_status");
            if (lowerInput.Contains("历史") || lowerInput.Contains("趋势"))
                return Task.FromResult("query_production_history");
            
            return Task.FromResult("general_inquiry");
        }

        private string FindPendingIntentFromHistory(string sessionId)
        {
            lock (_lockObject)
            {
                if (!_conversationStore.TryGetValue(sessionId, out var history) || history.Count == 0)
                {
                    return string.Empty;
                }

                // 回溯最近10条机器消息，寻找待承接的询问
                var recentBotMessages = history
                    .Where(h => !string.IsNullOrWhiteSpace(h.AssistantResponse))
                    .TakeLast(10)
                    .Select(h => h.AssistantResponse!)
                    .Reverse() // 从最新到最旧
                    .ToList();

                foreach (var botMsg in recentBotMessages)
                {
                    var intent = ExtractPendingIntentFromMessage(botMsg);
                    if (!string.IsNullOrWhiteSpace(intent))
                    {
                        _logger.LogInformation("从历史消息中找到待承接意图: {Intent}, 消息: {Message}", intent, botMsg);
                        return intent;
                    }
                }

                return string.Empty;
            }
        }

        private string ExtractPendingIntentFromMessage(string botMessage)
        {
            var lowerMsg = botMessage.ToLower();
            
            // 1) 运行状态相关询问
            if (lowerMsg.Contains("运行状态") || lowerMsg.Contains("设备状态") || lowerMsg.Contains("产线状态"))
            {
                return "follow_query_status";
            }
            
            // 2) 历史产量相关询问
            if (lowerMsg.Contains("历史产量") || lowerMsg.Contains("历史数据") || lowerMsg.Contains("产量趋势"))
            {
                return "follow_query_production_history";
            }
            
            // 3) 设备信息相关询问
            if (lowerMsg.Contains("设备名称") || lowerMsg.Contains("设备编号") || lowerMsg.Contains("产线编号"))
            {
                return "follow_query_device_info";
            }
            
            // 4) 时间范围相关询问
            if (lowerMsg.Contains("时间范围") || lowerMsg.Contains("最近") || lowerMsg.Contains("从") && lowerMsg.Contains("到"))
            {
                return "follow_query_time_range";
            }
            
            // 5) 工单相关询问
            if (lowerMsg.Contains("故障描述") || lowerMsg.Contains("紧急程度") || lowerMsg.Contains("工单信息"))
            {
                return "follow_query_work_order";
            }
            
            // 6) 权限相关询问
            if (lowerMsg.Contains("权限") || lowerMsg.Contains("授权") || lowerMsg.Contains("审批"))
            {
                return "follow_query_permission";
            }
            
            // 7) 通用选择询问（包含"或"、"还是"等选择词）
            if (lowerMsg.Contains("或") || lowerMsg.Contains("还是") || lowerMsg.Contains("选择"))
            {
                // 根据具体内容判断
                if (lowerMsg.Contains("运行") || lowerMsg.Contains("状态"))
                    return "follow_query_status";
                if (lowerMsg.Contains("历史") || lowerMsg.Contains("产量"))
                    return "follow_query_production_history";
                if (lowerMsg.Contains("设备") || lowerMsg.Contains("产线"))
                    return "follow_query_device_info";
            }
            
            return string.Empty;
        }

        private string GetLastAssistantMessage(string sessionId)
        {
            lock (_lockObject)
            {
                if (_conversationStore.TryGetValue(sessionId, out var history))
                {
                    var last = history.LastOrDefault(h => !string.IsNullOrWhiteSpace(h.AssistantResponse));
                    return last?.AssistantResponse ?? string.Empty;
                }
            }
            return string.Empty;
        }

        private async Task<CustomerServiceResponse?> TryGenerateWithOpenAIAsync(string userInput, string sessionId)
        {
            try
            {
                var cfg = _settings.Value.LangChain;
                if (string.IsNullOrWhiteSpace(cfg.OpenAIApiKey)) return null;

                // 构建消息上下文（包含最近若干轮）
                var messages = BuildChatMessages(sessionId, userInput);

                var req = new
                {
                    model = string.IsNullOrWhiteSpace(cfg.ModelName) ? "gpt-3.5-turbo" : cfg.ModelName,
                    messages,
                    temperature = cfg.Temperature,
                    max_tokens = cfg.MaxTokens
                };

                using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(Math.Max(5, cfg.RequestTimeoutSeconds)));
                // 兼容通义千问 DashScope OpenAI 格式
                var provider = (cfg.Provider ?? "OpenAI").Trim();
                var baseUrl = string.IsNullOrWhiteSpace(cfg.BaseUrl)
                    ? (provider.Equals("DashScope", StringComparison.OrdinalIgnoreCase) ? "https://dashscope.aliyuncs.com/compatible-mode/v1" : "https://api.openai.com/v1")
                    : cfg.BaseUrl!;

                var endpoint = $"{baseUrl.TrimEnd('/')}/chat/completions";
                using var reqMsg = new HttpRequestMessage(HttpMethod.Post, endpoint);
                reqMsg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", cfg.OpenAIApiKey);
                reqMsg.Content = new StringContent(JsonSerializer.Serialize(req), Encoding.UTF8, "application/json");

                var resp = await _httpClient.SendAsync(reqMsg, cts.Token);
                if (!resp.IsSuccessStatusCode)
                {
                    var err = await resp.Content.ReadAsStringAsync(cts.Token);
                    _logger.LogWarning("LLM响应非200: {Status} {Body}", resp.StatusCode, err);
                    return null;
                }

                using var stream = await resp.Content.ReadAsStreamAsync(cts.Token);
                using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cts.Token);

                var content = doc.RootElement
                    .GetProperty("choices")[0]
                    .GetProperty("message")
                    .GetProperty("content")
                    .GetString() ?? string.Empty;

                return new CustomerServiceResponse
                {
                    Content = content.Trim(),
                    Type = ResponseType.Text
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用LLM生成回复失败");
                return null;
            }
        }

        private List<object> BuildChatMessages(string sessionId, string userInput)
        {
            var sys = new
            {
                role = "system",
                content = "你是一个面向制造执行系统(MES)的一线智能客服。用简洁专业的中文回答，必要时主动追问关键信息；如涉及设备/产线编码(如 H0012)，按生产语境理解。无法确认时提示可转人工。"
            };

            var list = new List<object> { sys };

            lock (_lockObject)
            {
                if (_conversationStore.TryGetValue(sessionId, out var history))
                {
                    // 取最近 N 条历史，由配置决定
                    var maxTurns = Math.Max(0, _settings.Value.LangChain.HistoryMaxTurns);
                    var tail = maxTurns > 0 ? history.TakeLast(maxTurns) : history;
                    foreach (var msg in tail)
                    {
                        list.Add(new { role = "user", content = msg.UserInput });
                        if (!string.IsNullOrWhiteSpace(msg.AssistantResponse))
                        {
                            list.Add(new { role = "assistant", content = msg.AssistantResponse! });
                        }
                    }
                }
            }

            list.Add(new { role = "user", content = userInput });
            return list;
        }

        private async Task<CustomerServiceResponse> GenerateResponseAsync(string input, string intent, string sessionId)
        {
            try
            {
                var hasOpenAI = !string.IsNullOrWhiteSpace(_settings.Value.LangChain.OpenAIApiKey);
                _logger.LogInformation("LLM Enabled: {Enabled}; Model={Model}", hasOpenAI, _settings.Value.LangChain.ModelName);
                if (hasOpenAI)
                {
                    var ai = await TryGenerateWithOpenAIAsync(input, sessionId);
                    if (ai != null)
                    {
                        _logger.LogInformation("LLM 回复成功，长度={Length}", ai.Content?.Length ?? 0);
                        // 基于AI生成的文本，简易判断是否是追问
                        var type = InferResponseType(ai.Content ?? string.Empty);
                        ai.Type = type;
                        // 建议操作仍然根据意图给出
                        ai.SuggestedActions = GenerateSuggestedActionsAsync(intent);
                        return ai;
                    }
                    else
                    {
                        _logger.LogWarning("LLM 调用失败或空响应，回退到规则引擎");
                    }
                }

                // 回退：规则生成
                var response = GenerateResponseByIntentAsync(input, intent);
                response.SuggestedActions = GenerateSuggestedActionsAsync(intent);
                return response;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成回复时发生错误");
                throw;
            }
        }

        private ResponseType InferResponseType(string content)
        {
            if (string.IsNullOrWhiteSpace(content)) return ResponseType.Text;
            var qMarks = new[] { '？', '?' };
            return content.IndexOfAny(qMarks) >= 0 ? ResponseType.Question : ResponseType.Text;
        }

        private CustomerServiceResponse GenerateResponseByIntentAsync(string input, string intent)
        {
            return intent switch
            {
                "query_production" => new CustomerServiceResponse
                {
                    Content = "我来帮您查询生产信息。请提供具体的设备名称或生产线编号，我将为您查询当前生产状态。",
                    Type = ResponseType.Question
                },
                "follow_query_status" => new CustomerServiceResponse
                {
                    Content = "好的，我来为您查询设备运行状态。请确认设备或产线编号，我将检查其当前运行状态、报警信息和维护状态。",
                    Type = ResponseType.Question
                },
                "follow_query_production_history" => new CustomerServiceResponse
                {
                    Content = "明白，我来为您查询历史产量数据。请指定查询的时间范围（如：最近24小时、最近7天、本月、或具体起止日期），我将为您分析产量趋势。",
                    Type = ResponseType.Question
                },
                "follow_query_device_info" => new CustomerServiceResponse
                {
                    Content = "好的，我来为您查询设备详细信息。请提供设备或产线编号，我将查询其基本信息、技术参数、维护记录和当前状态。",
                    Type = ResponseType.Question
                },
                "follow_query_time_range" => new CustomerServiceResponse
                {
                    Content = "请指定查询的时间范围，我可以为您提供：最近1小时、最近24小时、最近7天、本月、本季度，或者您指定的具体起止日期范围。",
                    Type = ResponseType.Question
                },
                "follow_query_work_order" => new CustomerServiceResponse
                {
                    Content = "好的，我来帮您完善工单信息。请提供：设备名称/编号、故障现象描述、紧急程度（高/中/低）、影响范围、联系人及联系方式。",
                    Type = ResponseType.Question
                },
                "follow_query_permission" => new CustomerServiceResponse
                {
                    Content = "权限申请需要确认您的身份和操作范围。请提供：操作类型、影响范围、申请原因、预计影响时间，我将为您提交审批申请。",
                    Type = ResponseType.Question
                },
                "query_status" => new CustomerServiceResponse
                {
                    Content = "我来为您查询设备运行状态。请提供设备或产线编号，我将检查其运行状态、报警信息、维护计划和性能指标。",
                    Type = ResponseType.Question
                },
                "query_production_history" => new CustomerServiceResponse
                {
                    Content = "我来为您查询历史产量数据。请提供设备/产线编号和时间范围，我将为您分析产量趋势、效率变化和异常情况。",
                    Type = ResponseType.Question
                },
                "create_work_order" => new CustomerServiceResponse
                {
                    Content = "我来帮您创建维护工单。请提供以下信息：设备名称/编号、故障现象描述、紧急程度（高/中/低）、影响范围、联系人及联系方式。",
                    Type = ResponseType.Action
                },
                "handle_alarm" => new CustomerServiceResponse
                {
                    Content = "设备报警处理需要根据具体情况来操作。请告诉我报警代码或报警描述，我将为您提供相应的处理方案和操作指导。",
                    Type = ResponseType.Text
                },
                "view_manual" => new CustomerServiceResponse
                {
                    Content = "我来帮您查找相关的操作手册。请告诉我您需要查看哪个设备或流程的说明文档，我将为您提供相应的技术资料和操作指南。",
                    Type = ResponseType.Question
                },
                "adjust_schedule" => new CustomerServiceResponse
                {
                    Content = "生产计划调整需要相应的权限和审批流程。请告诉我您希望调整的具体内容、调整原因和预期影响，我将为您评估可行性并提交审批申请。",
                    Type = ResponseType.Action
                },
                _ => new CustomerServiceResponse
                {
                    Content = "我理解您的问题，但可能需要更多信息来提供准确的帮助。请详细描述您的具体需求，我将为您提供专业的解决方案。",
                    Type = ResponseType.Question
                }
            };
        }

        private List<SuggestedAction> GenerateSuggestedActionsAsync(string intent)
        {
            var actions = new List<SuggestedAction>();
            
            switch (intent)
            {
                case "query_production":
                    actions.Add(new SuggestedAction
                    {
                        Title = "查询设备产量",
                        Description = "查看指定设备的当前产量、效率指标和运行状态",
                        Type = ActionType.QueryProduction
                    });
                    // 承接项：运行状态 / 历史产量
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看运行状态",
                        Description = "检查设备运行状态、报警信息和维护计划",
                        Type = ActionType.QueryStatus
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看历史产量",
                        Description = "分析指定时间范围内的产量趋势和效率变化",
                        Type = ActionType.QueryProductionHistory
                    });
                    break;
                case "create_work_order":
                    actions.Add(new SuggestedAction
                    {
                        Title = "创建维护工单",
                        Description = "为设备故障或维护需求创建标准化工单",
                        Type = ActionType.CreateWorkOrder
                    });
                    break;
                case "handle_alarm":
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看故障手册",
                        Description = "获取设备故障处理的标准操作流程",
                        Type = ActionType.ViewManual
                    });
                    break;
                case "follow_query_status":
                case "query_status":
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看运行状态",
                        Description = "实时监控设备运行状态、报警信息和维护状态",
                        Type = ActionType.QueryStatus
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看报警历史",
                        Description = "查看设备历史报警记录和处理情况",
                        Type = ActionType.ViewAlarmHistory
                    });
                    break;
                case "follow_query_production_history":
                case "query_production_history":
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看历史产量",
                        Description = "分析产量趋势、效率变化和异常情况",
                        Type = ActionType.QueryProductionHistory
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "导出产量报告",
                        Description = "生成指定时间范围的产量分析报告",
                        Type = ActionType.ExportReport
                    });
                    break;
                case "follow_query_device_info":
                    actions.Add(new SuggestedAction
                    {
                        Title = "查询设备信息",
                        Description = "查看设备基本信息、技术参数和配置",
                        Type = ActionType.QueryDeviceInfo
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看维护记录",
                        Description = "查看设备维护历史和保养计划",
                        Type = ActionType.ViewManual
                    });
                    break;
                case "follow_query_time_range":
                    actions.Add(new SuggestedAction
                    {
                        Title = "设置时间范围",
                        Description = "选择查询的时间段和粒度",
                        Type = ActionType.SetTimeRange
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "快速时间选择",
                        Description = "常用时间段：最近1小时、24小时、7天、本月",
                        Type = ActionType.QueryProductionHistory
                    });
                    break;
                case "follow_query_work_order":
                    actions.Add(new SuggestedAction
                    {
                        Title = "完善工单信息",
                        Description = "补充工单的详细描述和要求",
                        Type = ActionType.CreateWorkOrder
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看工单模板",
                        Description = "参考标准工单模板和填写规范",
                        Type = ActionType.ViewManual
                    });
                    break;
                case "follow_query_permission":
                    actions.Add(new SuggestedAction
                    {
                        Title = "申请操作权限",
                        Description = "提交权限申请表单和审批流程",
                        Type = ActionType.ApplyPermission
                    });
                    actions.Add(new SuggestedAction
                    {
                        Title = "查看权限说明",
                        Description = "了解不同操作类型的权限要求",
                        Type = ActionType.ViewManual
                    });
                    break;
            }
            
            // 通用操作
            actions.Add(new SuggestedAction
            {
                Title = "联系人工客服",
                Description = "转接专业人工客服处理复杂问题",
                Type = ActionType.ContactHuman
            });
            
            return actions;
        }

        private void SaveConversationHistory(string sessionId, ConversationHistory history)
        {
            lock (_lockObject)
            {
                if (!_conversationStore.ContainsKey(sessionId))
                {
                    _conversationStore[sessionId] = new List<ConversationHistory>();
                }
                _conversationStore[sessionId].Add(history);
            }
        }
    }
} 